/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.UserSalaryRulesHistory;
import org.springblade.modules.admin.enums.StatusEnum;
import org.springblade.modules.admin.service.IUserSalaryRulesHistoryService;
import org.springblade.modules.admin.vo.user.SalaryVo;
import org.springblade.modules.admin.vo.user.UserSalaryTemplateVo;
import org.springblade.modules.admin.vo.user.UserWithoutVo;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.service.IDictService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.UserSalaryRules;
import org.springblade.modules.admin.vo.UserSalaryRulesVO;
import org.springblade.modules.admin.wrapper.UserSalaryRulesWrapper;
import org.springblade.modules.admin.service.IUserSalaryRulesService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户工资表 控制器
 *
 * @author ysq
 * @since 2025-05-23
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/usersalaryrules")
@Api(value = "用户工资表", tags = "用户工资表接口")
public class UserSalaryRulesController extends BladeController {

	private final IUserSalaryRulesService userSalaryRulesService;

	private final IUserSalaryRulesHistoryService userSalaryRulesHistoryService;

	private final IDictService dictService;

	@GetMapping("list")
	@ApiOperation("获取规则列表")
	public R<List> list(Long templateId, Integer status, Long salaryMonthId) {
		List<UserSalaryRules> userSalaryRules;
		if (salaryMonthId != null) {
			List<UserSalaryRulesHistory> historyList = userSalaryRulesHistoryService.list(Wrappers.<UserSalaryRulesHistory>lambdaQuery().eq(UserSalaryRulesHistory::getSalaryMonthId, salaryMonthId).eq(UserSalaryRulesHistory::getStatus, 1).orderByAsc(UserSalaryRulesHistory::getSort));
			return R.data(historyList);
		}
		if (status != null) {
			userSalaryRules = userSalaryRulesService.list(Wrappers.<UserSalaryRules>lambdaQuery().eq(UserSalaryRules::getTemplateId, templateId).eq(UserSalaryRules::getStatus, StatusEnum.ENABLE.getId()).orderByAsc(UserSalaryRules::getSort));
		} else {
			userSalaryRules = userSalaryRulesService.list(Wrappers.<UserSalaryRules>lambdaQuery().eq(UserSalaryRules::getTemplateId, templateId).orderByAsc(UserSalaryRules::getSort));
		}
		if (userSalaryRules.size() > 0) {
			List<Dict> dictList = dictService.getList("user_elevator_skill_type");
			List<UserSalaryRules> collect = userSalaryRules.stream().filter(o -> o.getRulesType() == 16).collect(Collectors.toList());
			if (collect.size() > 0) {
				UserSalaryRules salaryRules = collect.get(0);
				userSalaryRules.remove(salaryRules);
				userSalaryRules.add(skillTypeInit(salaryRules, dictList));
			}
			List<UserSalaryRules> collect1 = userSalaryRules.stream().filter(o -> o.getRulesType() == 27).collect(Collectors.toList());
			if (collect1.size() > 0) {
				UserSalaryRules salaryRules = collect1.get(0);
				userSalaryRules.remove(salaryRules);
				userSalaryRules.add(skillTypeInit(salaryRules, dictList));
			}
		}
		userSalaryRules.sort(Comparator.comparingInt(UserSalaryRules::getSort));
		return R.data(userSalaryRules);
	}

	private UserSalaryRules skillTypeInit(UserSalaryRules salaryRules, List<Dict> dictList) {
		List<SalaryVo> rulesDetail = new ArrayList<>();
		Map<String, List<SalaryVo>> listMap = salaryRules.getRulesDetail().stream().collect(Collectors.groupingBy(SalaryVo::getKey));
		for (Dict dict : dictList) {
			if (dict.getParentId() != 0) {
				SalaryVo salaryVo = new SalaryVo();
				salaryVo.setKey(dict.getDictValue());
				salaryVo.setKeyId(Convert.toInt(dict.getDictKey()));
				List<SalaryVo> salaryVos = listMap.get(dict.getDictValue());
				if (salaryVos != null && salaryVos.size() > 0) {
					salaryVo.setValue(salaryVos.get(0).getValue());
				} else {
					salaryVo.setValue("0");
				}
				salaryVo.setValueType(1);
				rulesDetail.add(salaryVo);
			}
		}
		rulesDetail.sort(Comparator.comparingInt(SalaryVo::getKeyId));
		salaryRules.setRulesDetail(rulesDetail);
		return salaryRules;
	}

	@PostMapping("update")
	@ApiOperation("更新规则")
	public R<Boolean> update(@RequestBody UserSalaryRules userSalaryRules) {
		userSalaryRulesService.saveOrUpdate(userSalaryRules);
		return R.data(true);
	}

	@PostMapping("update/batch")
	@ApiOperation("批量更新规则")
	public R<Boolean> updateBatch(@RequestBody List<UserSalaryRules> userSalaryRules) {
		Integer status = userSalaryRules.get(0).getStatus();
		if (status != null) {
			Map<Long, List<UserSalaryRules>> listMap = userSalaryRules.stream().collect(Collectors.groupingBy(UserSalaryRules::getId));
			Long id = userSalaryRules.get(0).getId();
			Long templateId = userSalaryRulesService.getById(id).getTemplateId();
			List<UserSalaryRules> userSalaryRules2 = userSalaryRulesService.list(Wrappers.<UserSalaryRules>lambdaQuery().eq(UserSalaryRules::getTemplateId, templateId));
			for (UserSalaryRules userSalaryRules1 : userSalaryRules2) {
				userSalaryRules1.setStatus(StatusEnum.DISABLE.getId());
				List<UserSalaryRules> list = listMap.get(userSalaryRules1.getId());
				if (list != null && list.size() > 0) {
					userSalaryRules1.setStatus(StatusEnum.ENABLE.getId());
				}
			}
			userSalaryRulesService.saveOrUpdateBatch(userSalaryRules);
		} else {
			userSalaryRulesService.saveOrUpdateBatch(userSalaryRules);
		}
		return R.data(true);
	}


	@GetMapping("template/list")
	@ApiOperation("模板列表")
	public R<List<UserSalaryTemplateVo>> templateList(String templateName) {
		List<UserSalaryTemplateVo> list = userSalaryRulesService.templateList(templateName);
		return R.data(list);
	}

	@PostMapping("template/update")
	@ApiOperation("模板更新")
	public R<Boolean> updateTemplate(@RequestBody UserSalaryRules userSalaryRules) {
		userSalaryRulesService.updateTemplate(userSalaryRules);
		return R.data(true);
	}


	@GetMapping("template/delete")
	@ApiOperation("删除模板")
	public R<Boolean> deleteTemplate(Long templateId) {
		userSalaryRulesService.remove(Wrappers.<UserSalaryRules>lambdaQuery().eq(UserSalaryRules::getTemplateId, templateId));
		return R.data(true);
	}


	@GetMapping("template/add")
	@ApiOperation("添加模板")
	public R<Boolean> addTemplate(String templateName) {
		List<UserSalaryRules> list = userSalaryRulesService.list(Wrappers.<UserSalaryRules>lambdaQuery().eq(UserSalaryRules::getTemplateName, templateName));
		if (list.size() > 0) {
			throw new ServiceException("模板名称不能相同");
		}
		List<UserSalaryRules> userSalaryRules = userSalaryRulesService.list(Wrappers.<UserSalaryRules>lambdaQuery().eq(UserSalaryRules::getTemplateId, 0).orderByAsc(UserSalaryRules::getRulesType));
		Long templateId = Convert.toLong(RandomUtil.randomNumbers(15));
		for (UserSalaryRules userSalaryRules1 : userSalaryRules) {
			userSalaryRules1.setId(null);
			userSalaryRules1.setStatus(0);
			userSalaryRules1.setTemplateName(templateName);
			userSalaryRules1.setTemplateId(templateId);
			userSalaryRules1.setCreateTime(null);
		}
		userSalaryRulesService.saveBatch(userSalaryRules);
		return R.data(true);
	}
}
